<?php

namespace App\Services\Group;

use App\Models\Activity\Activity;
use App\Models\Group\Group;
use App\Models\Group\GroupMembers;
use App\Models\Posts\Posts;
use App\Models\School\Position;
use App\Models\Store\Store;
use App\Models\Vote\Vote;
use App\Models\Member\Member;
use App\Models\School\Manager;
use App\Models\Vote\VoteItem;
use App\Services\Talking\TalkingService;
use App\Services\Com\UtilService;
use App\Services\Easemob\Groups;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class GroupService
{
    /**
     * 添加学校群管理员
     * @param $school_uuid
     * @param $position_uuid
     * @param $member_uuid
     * @return bool
     * @throws \Exception
     */
    public static function setSchoolGroupMananger($school_uuid, $position_uuid, $member_uuid){
        try {
            DB::beginTransaction();

            $postion = Position::where('uuid','=', $position_uuid)->first();
            if(empty($postion)) throw new \Exception('没有该职位~');

            $managerNum = Manager::where('school_uuid','=',$school_uuid)
                ->where('position_uuid','=',$position_uuid)
                ->count();
            if($managerNum >= $postion->num)  throw new \Exception('该学校当前职位人数已满~');

            //删除老职位
            Manager::where('member_uuid', '=', $member_uuid)->delete();

            $param['position_uuid'] = $position_uuid;
            $param['school_uuid'] = $school_uuid;
            $param['member_uuid'] = $member_uuid;
            Manager::create($param);

            $groupSchool = Group::where('service_type', '=', 'school')->where('service_uuid','=',$school_uuid)->first();
            if(empty($groupSchool))   throw new \Exception('此人的学校群没有~');

            $groupMember = GroupMembers::where('member_uuid','=',$member_uuid)->where('group_id', $groupSchool->group_id)->first();
            if(empty($groupMember)){
                //db, im 加人
                $save_data['group_members'] = [$member_uuid];
                $save_data['group_id'] = $groupSchool->group_id;
                $save_data['type'] = 2;

                self::addMembersGroup($save_data);
            }else{
                //在群里，但是普通成员
                if($groupMember->type != 3)    throw new \Exception('当前用户不是普通成员~');
                //im 加管理
                $param_admin_im['group_member'] = $member_uuid;
                $param_admin_im['group_id'] = $groupSchool->group_id;
                Groups::addGroupAdmin($param_admin_im);
                //db 变更为管理
                $groupMember->update(['type' => 2]);
            }

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage().$e->getLine());
        }

        return true;
    }

    /**
     * 删除学校群管理员
     * @param $school_uuid
     * @param $position_uuid
     * @param $member_uuid
     * @return bool
     * @throws \Exception
     */
    public static function delSchoolGroupMananger($school_uuid, $position_uuid, $member_uuid){
        try {
            DB::beginTransaction();

            $postion = Position::where('uuid','=', $position_uuid)->first();
            if(empty($postion)) throw new \Exception('没有该职位~');

            $groupSchool = Group::where('service_type', '=', 'school')->where('service_uuid','=',$school_uuid)->first();
            if(empty($groupSchool))   throw new \Exception('此人的学校群没有~');

            $groupMember = GroupMembers::where('member_uuid','=',$member_uuid)->where('group_id', $groupSchool->group_id)->first();
            if(empty($groupMember))   throw new \Exception('当前用户没有在学校群里~');

            $groupMember->update(['type' => 3]);

            $manager = Manager::where('school_uuid', $school_uuid)->where('member_uuid', $member_uuid)->first();
            $manager->delete();

            $groupParam = [];
            $groupParam['group_member'] = $member_uuid;
            $groupParam['group_id'] = $groupSchool->group_id;

            $groupResult = Groups::removeGroupAdmin($groupParam);

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage().$e->getLine());
        }

        return true;
    }

    /**
     * $s = GroupService::userJoinSchoolTalking();
     * var_dump($s);
     * die;
     * 同步全部用户加入到学校talking
     * 学校管理员，成为talking 管理员
     * @return 
     */
    public static function userJoinSchoolTalking(){
            
            set_time_limit(0);
            $member_all = Member::where('school_uuid','<>','')->where('state','=',200)->get();

            foreach ($member_all as $key => $value) {

                $group = Group::where('service_type', '=', 'school')->where('service_uuid', '=', $value['school_uuid'])->first();
                //建立此学校群
                if(empty($group)){
                    //新学校，建群，加成员
                    // var_dump($value['uuid']);die;
                    $c_res = TalkingService::userSchoolTalkingCreateAndJoin($value['uuid'], $value['school_uuid']);
                    // var_dump($c_res);die;
                    if(!isset($c_res['code'])){
                        var_dump($c_res,$value->toArray());die;
                    }
                    if($c_res['code'] != 200){
                        Log::info('报错了');
                        var_dump($c_res);
                    }
                    $group = Group::where('service_type', '=', 'school')->where('service_uuid', '=', $value['school_uuid'])->first();
                }

                //群存在
                if(!empty($group)){
                    $groupMembers = GroupMembers::where('group_id', '=', $group->group_id)->where('member_uuid','=',$value['uuid'])->first();
                    //此人不在此群
                    if(empty($groupMembers)){
                        $member_type = 3; //成员在群的角色
                        $manager = Manager::where('member_uuid','=',$value['uuid'])->where('school_uuid','=',$value['school_uuid'])->first();
                        if(!empty($manager)){
                            $member_type = 2; //成员在群 为管理
                        }

                        $save_data['group_members'] = [$value['uuid']];
                        $save_data['group_id'] = $group->group_id;
                        $save_data['type'] = $member_type;

                        //im 加人，db 加人
                        try {
                            self::addMembersGroup($save_data);    
                        } catch (\Exception $e) {
                            $s = ['code' => $e->getCode(), 'message' => $e->getMessage()??'fail！'];
                            var_dump($s);
                        }
                    }

                    //此人在群，判断是否学校管理，是就更改为学校群的管理
                    if(!empty($groupMembers)){
                        $member_type = 3; //成员在群的角色
                        $manager = Manager::where('member_uuid','=',$value['uuid'])->where('school_uuid','=',$value['school_uuid'])->first();
                        if(!empty($manager)){
                            //im 变管理
                            $param['group_member'] = $value['uuid'];
                            $param['group_id'] = $group->group_id;
                            $result = Groups::addGroupAdmin($param);
                            //db 变管理
                            $member_type = 2;
                            GroupMembers::where('group_id', $group->group_id)->where('member_uuid', $value['uuid'])->update(['type' => $member_type]);
                        }
                    }
                }
            }

            return ['code' => 200, 'message' => '成功'];
    }

    /**
     * @param $param group_members arr
     * @param $param type
     * @param $param group_id
     * @return array
     * 错误结果说明 
     * http://docs-im-beta.easemob.com/document/server-side/error.html#%E7%B4%A2%E5%BC%95-%E9%94%99%E8%AF%AF%E7%BB%93%E6%9E%9C%E8%AF%B4%E6%98%8E
     * 添加群成员
     */
    public static function addMembersGroup($param){

        try {
            $result = Groups::addMembersGroup($param);
            if (!empty($result['code'])) {
                
                Log::alert('$resultcode:'.json_encode($param).$result['code']);
                $msg = ($result['error'] ?? '') . ':' . ($result['error_description'] ?? '');
                
                if($result['code'] == 403){
                    $msg = '该好友已在群聊中，无需再次添加';
                }
                throw new \Exception($msg, $result['code']);
                
            }

            // 新增组成员
            $datas = [];
            foreach ($param['group_members'] as $member) {
                if(empty($member)){
                    Log::alert('$member为空'.$member);
                }
                $cache_key = config('cache.key_list.chat_status').md5($param['group_id'].$member);
                $chat_status = Cache::get($cache_key);

                $data    = [
                    'member_uuid' => $member,
                    'owner_uuid'  => UtilService::memberUuidToImAccount($member),
                    'group_id'    => $param['group_id'],
                    'type'        => $param['type'] ?? 3,
                    'chat_status' => $chat_status ?? 0, //0=正常，：1=禁言
                    'uuid'        => Str::uuid(),
                ];
                $datas[] = $data;
                //历史有禁言
                if($chat_status == 1){
                    $mute_param['group_id'] = $param['group_id'];
                    $mute_param['chat_status'] = $chat_status;
                    $mute_param['member_uuid'] = $member;
                    $result_api = Groups::groupMemberMute($mute_param);
                    if (!$result_api) {
                        Log::alert('addMembersGroup 禁言API异常');
                    }
                }
            }
            $save = GroupMembers::insert($datas);

            return ['code' => 200, 'message' => '成功'];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'message' => $e->getMessage()??'fail！'];
        }
    }


    /**
     * @param $param['group_members'] array 
     * @param $param['group_id'] int
     * @return array
     * 移除组成员 todo bug fix
     */
    public static function removeMembersGroup($param = [])
    {
        try {

            $result = Groups::removeMembersGroup($param);
            if (!empty($result['code'])) {
                throw new \Exception(($result['error'] ?? '') . ':' . ($result['error_description'] ?? ''), $result['code']);
            }
            // 删除组成员
            $result = GroupMembers::query()->where('group_id', $param['group_id'])->whereIn('member_uuid', $param['group_members'])->delete();
            if(!$result){
                //return $this->failure('删除本地数据失败');
                throw new \Exception('删除本地数据失败', 1);
            }
            return ['code' => 200, 'message' => '成功'];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'message' => $e->getMessage()??'fail！'];
        }
    }

}
